<?php
/**
 * @author: Cocoh
 * @email: cocoh@dwebsite.com
 * @on: 2008/11/04
 *
 */
Zend_Loader::loadClass("Orbital");
Zend_Loader::loadClass("CodesUtility");
class CardPaymentUtility
{
		
	const CC_DATA_SALT = '!T01nK5!';
	
	
	function payViaAuthorizeNetGateway($data, $conf, $total, $isCredit = 0)
	{
		Zend_Loader::loadClass("Authorizenet");
		
		$gateway_ok = true;
		$operation_xid = 0;
		if(!isset($conf->payment->payment_gateway))
		{
			$ret_result = 'Config error: parameters are not properly set';
			$gateway_ok = false;
		}
		if(!isset($conf->authorizenet->login))
		{
			$ret_result = 'Config error: Merchant login not set';
			$gateway_ok = false;
		}
		if(!isset($conf->authorizenet->password))
		{
			$ret_result = 'Config error: Merchant password not set';
			$gateway_ok = false;
		}
		if($gateway_ok)
		{
			$a = new Authorizenet();
			
			$a->add_field('x_login', $conf->authorizenet->login);
			$a->add_field('x_tran_key', trim($conf->authorizenet->password) );
			

	        $a->add_field('x_version', '3.1');
	        $a->add_field('x_type', 'AUTH_CAPTURE');
	        $a->add_field('x_test_request', 'FALSE');
	        $a->add_field('x_relay_response', 'FALSE');

	        $a->add_field('x_delim_data', 'TRUE');
	        $a->add_field('x_delim_char', '|');     
	        $a->add_field('x_encap_char', '');

	        $a->add_field('x_first_name', $data->payer->first_name);
	        $a->add_field('x_last_name', $data->payer->last_name);
	        $a->add_field('x_address', $data->payer->address);
	        $a->add_field('x_city', $data->payer->city);
	        $a->add_field('x_state', $data->payer->state_code);
	        $a->add_field('x_zip', $data->payer->zip);
	        $a->add_field('x_country', $data->payer->country); 
	        $a->add_field('x_email', $data->payer->email);
	        $a->add_field('x_phone', $data->payer->contact_phone);

	        $a->add_field('x_method', 'CC');
	        $a->add_field('x_card_num', preg_replace('/\D/', '', $data->credit_card->cc_number));
			
	        $a->add_field('x_amount',  $total);
	        $a->add_field('x_exp_date', $data->credit_card->expiration_month.$data->credit_card->expiration_year);
	        $a->add_field('x_card_code', preg_replace('/\D/', '', $data->credit_card->code));

	        // Process the payment and output the results
			CardPaymentUtility::logMsg($a->dump_fields());
			$ch_ret = $a->process();
			CardPaymentUtility::logMsg($a->dump_response());
	        if ($ch_ret == 1) {
	            $ret_result = 1;
				$operation_xid = $a->response['Transaction ID'];
	        }else{
				$ret_result = $a->get_response_reason_text();
			}
		}
		CardPaymentUtility::logMsg($ret_result);
		$ret->result = $ret_result;
		$ret->operation_xid = $operation_xid;
		return $ret;
	}
	
	
 	
	function payViaTransactionCentralGateway($data, $conf, $total, $isCredit = 0)
	{
		Zend_Loader::loadClass("TransactionCentral");

		$operation_xid = 0;
		$tc_gateway_ok = true;

		$params = array();

		if(0){ 
			$params['MerchantID'] = TC_TEST_MERCHANTID;
			$params['RegKey'] = TC_TEST_REGKEY;
		} else {
			if(!isset($conf->payment->payment_gateway))
			{
				$ret_result = 'Config error: parameters are not properly set';
				$tc_gateway_ok = false;
			}
			if(!isset($conf->tc_gateway->merchant_id))
			{
				$ret_result = 'Config error: Merchant ID not set';
				$tc_gateway_ok = false;
			}
			if(!isset($conf->tc_gateway->reg_key))
			{
				$ret_result = 'Config error: Merchant reg key not set';
				$tc_gateway_ok = false;
			}
			if($tc_gateway_ok)
			{
				$params['MerchantID'] = (int) $conf->tc_gateway->merchant_id;
				$params['RegKey'] = trim($conf->tc_gateway->reg_key);
			}
		}
		if($tc_gateway_ok)
		{
			if($isCredit)
			{
				$params['CreditAmount'] = $total;
				$params['TransID'] = (int) $data->payment->operation_xid;

				$post_url = TC_CCCREDIT_URL;
			} else
			{
				$cc_year = $data->credit_card->expiration_year;
				if($cc_year >= 2000)
					$cc_year -= 2000;
				else
					$cc_year -= 1900;

				$params['Amount'] = $total;
				$params['AccountNo'] = preg_replace('/\D/', '', $data->credit_card->cc_number);
				
				$params['CVV2'] = preg_replace('/\D/', '', $data->credit_card->code);
				$params['NameonAccount'] = strtoupper($data->payer->first_name . ' ' . $data->payer->last_name );
				$params['CCMonth'] = sprintf("%02d", (int) $data->credit_card->expiration_month);
				$params['CCYear'] = sprintf("%02d", (int) $cc_year);
				$params['REFID'] = $data->payer->id . '-' . date('YmdHis');
				$params['AVSADDR'] = strtoupper($data->payer->address);
				$params['AVSZIP'] = strtoupper($data->payer->zip);

				$post_url = TC_CCSALE_URL;
			}
			CardPaymentUtility::logParams($params, $post_url);
			$ch_ret = TransactionCentral::process($params , $post_url);
			CardPaymentUtility::logMsg($ch_ret);
			
			
			if ($ch_ret)
			{
				if(preg_match('/.*\<body\>\s*(\S.*\S)\s*\<\/body\>.*/', $ch_ret, $hits))
				{
					parse_str($hits[1], $retA);
					if(strtolower($retA['Auth']) == 'declined' ||
						strlen(trim($retA['Auth'])) == 0 ||
						(int) $retA['TransID'] == 0 ||
						strtolower($retA['Status']) == 'f')
					{
						$ret_result = 'Fatal error: ' . $retA['Notes'];
					} else
					{
						$ret_result = 1;
						$operation_xid = $retA['TransID'];
					}
				} else{
					$ret_result = 'Fatal error: The payment gateway processor returned an unrecognized data. ' . $ch_ret;
				}
			}else{
				$ret_result = 'Error: Payment operation not supported';
			} 
			
		}
		CardPaymentUtility::logMsg($ret_result);
		$ret->result = $ret_result;
		$ret->operation_xid = $operation_xid;
		return $ret;
		
	}
	
	
	
	
	
 	function payViaOrbitalGateway($data, $conf, $total, $isCredit = 0)
 	{		
		Zend_Loader::loadClass("BaseView");

		$classView = new BaseView();
		$classView->setNoLayout();
		
		$classView->assign("payer", $data->payer);
		$classView->assign("credit_card", $data->credit_card);
		//$classView->assign("CardBrand", $data->credit_card->card_type);
		
		
		$classView->assign("BIN", $conf->orbital->BIN);
		$classView->assign("MerchantID", $conf->orbital->MerchantID);
		
		if ($conf->orbital->TerminalID){
			$classView->assign("TerminalID", $conf->orbital->TerminalID);
		}else{
			$classView->assign("TerminalID", '001');
		}
		
		/*force 2 decimals*/
		$newTotal = number_format($total, 2);
		$formattedTotal = str_replace(".","",$newTotal);
		$classView->assign("total", $formattedTotal);
		
		$order_id = $data->payer->id . '-' . date('YmdHis');
		$classView->assign("OrderID", $order_id);
		
		$cc_year = $data->credit_card->expiration_year;
		
		if($cc_year >= 2000)	$cc_year -= 2000;
		else					$cc_year -= 1900;
		
		$CardSecVal = preg_replace('/\D/', '', $data->credit_card->code);
		$AVSaddress1 = strtoupper($data->payer->address);
		$Exp = sprintf("%02d%02d", (int) $data->credit_card->expiration_month, (int) $cc_year);
		
		$classView->assign("CardSecVal", $CardSecVal);
		$classView->assign("AVSaddress1", $AVSaddress1);
		$classView->assign("Exp", $Exp);
		
		if ($isCredit) {
			
			
			$TxRefNum = $data->payment->operation_xid;
			$TxRefIdx = 0;
			
			$classView->assign("TxRefNum", $TxRefNum);
			$classView->assign("TxRefIdx", $TxRefIdx);
			
			$transaction_date = date('Y-m-d', strtotime($data->payment->transaction_date));

			if ($transaction_date == date('Y-m-d')){
				$classView->setTemplateDir(DEFAULT_DIR . "views/globals/");
				$classView->setTemplate('orbitalreversal.xml');
				$xml = $classView->getHTML(); 
								
			}else{
				$classView->assign("MessageType", 'R');
				$classView->assign("Comments", "Refund from School Age Child Care");
				
				$classView->setTemplateDir(DEFAULT_DIR . "views/globals/");
				$classView->setTemplate('orbitalneworder.xml');
				$xml = $classView->getHTML(); 
			}
			
		} else {
			$classView->assign("MessageType", 'AC');
			$classView->assign("Comments", "Payment from School Age Child Care");
			
			$classView->setTemplateDir(DEFAULT_DIR . "views/globals/");
			$classView->setTemplate('orbitalneworder.xml');
			$xml = $classView->getHTML();
		}
		
		$tempReplaceStr = $data->credit_card->cc_number;
		$tempNewVal = substr($tempReplaceStr, -4);
		$tempXml = str_replace($tempReplaceStr, $tempNewVal, $xml);
		CardPaymentUtility::logXml ("\n".date("D M j G:i:s T Y - ").$tempXml);
		
		if ($xml){
			$orbital = new Orbital($xml);
			
			$result = $orbital->process();
			
			CardPaymentUtility::logResult ($result);
	
			if (empty($result))
				$ret_result = "General problem trying to reach Orbital Payment Gateway.";
			else {
				if ($isCredit) {
					if (isset($result['Response'][0]['NewOrderResp'])) {
						$response = $result['Response'][0]['NewOrderResp'][0];
					} else {
						$response = $result['Response'][0]['ReversalResp'][0];
					}
					if ($response['ProcStatus'][0] == 0 && !empty($response['TxRefNum'][0])) {
					//if ((isset($response['ProcStatus'][0]) && $response['ProcStatus'][0] == 0) && !is_array($result['Response'][0]['QuickResp'])) 
						$ret_result = 1;
						$operation_xid = $response['TxRefNum'][0];
					} else {
						if (is_array($result['Response'][0]['QuickResp']))
							$ret_result = 'Fatal error: ' . $result['Response'][0]['QuickResp'][0]['StatusMsg'][0];
						else
							$ret_result = 'Fatal error: ' . $response['RespCode'][0] . ' : ' . $response['RespMsg'][0];
					}
				} else {
					$response = $result['Response'][0]['NewOrderResp'][0];
	
					if ($response['ProcStatus'][0] == 0 && $response['ApprovalStatus'][0] == 1){ // SUCCESS
						$ret_result = 1;
						$operation_xid = $response['TxRefNum'][0];
					}
					else { // FAILED
						if (is_array($result['Response'][0]['QuickResp']))
							$ret_result = 'Fatal error: ' . $result['Response'][0]['QuickResp'][0]['StatusMsg'][0];
						else
							$ret_result = 'Fatal error: ' . $response['RespCode'][0] . ' : ' . $response['RespMsg'][0];
					}
				}
			}
		}else{
			$ret_result = 'Error: Payment operation not supported';
		}
		
		$ret->result = $ret_result;
		$ret->operation_xid = $operation_xid;
		return $ret;		
 	}
 	
 	
 	/**
 	 * @param data - contains the ff fields: 
 	 * payer->id
 	 * payer->last_name 
 	 * payer->first_name
 	 * payer->zip
 	 * payer->city
 	 * payer->state
 	 * payer->address
 	 * payer->email
 	 * payer->contact_phone
 	 * credit_card->card_type
 	 * credit_card->cc_number
 	 * credit_card->expiration_month
 	 * credit_card->expiration_year
 	 * credit_card->code
 	 * 
	 * payment->operation_xid
	 * payment->transaction_date - orbital only
	 *
 	 * @param total - total payment
 	 * @param conf - configuration file contents
 	 * 
 	 * 
 	 */
 	function payByCreditCard($data, $total, $conf, $isCredit = 0)
 	{ 		
 		$result->value = 1;
 		$result->code = CodesUtility::TRANSACTION_CODE_SUCCESS;
 		$result->msg = "";
 		
 		$card_num = substr($data->credit_card->cc_number, -4);
		$userid = AuthUtility::getCurrentUserId();
		CardPaymentUtility::logMsg("Verifying : " . $data->payer->last_name . " " . $data->credit_card->card_type . "-$card_num" . " userid: $userid" );
	 	
		if(!$conf->payment->gateway_enabled){ 
			$result->value = 1;
			$result->code = CodesUtility::TRANSACTION_CODE_SUCCESS;
			$result->msg = "";
			$result->operation_xid = "DUMMYXID". date("YmdGis");
		}else{
	 		if ($conf->payment->payment_gateway == 'orbital'){
	 			$ret_result = CardPaymentUtility::payViaOrbitalGateway($data, $conf, $total, $isCredit);
	 		}elseif($conf->payment->payment_gateway == 'tc_gateway') {
				$ret_result = CardPaymentUtility::payViaTransactionCentralGateway($data, $conf, $total, $isCredit);
			}elseif($conf->payment->payment_gateway == 'authorizenet') {
				$ret_result = CardPaymentUtility::payViaAuthorizeNetGateway($data, $conf, $total, $isCredit);
			}
				
			if ($ret_result->result == 1){
				$result->value = 1;
				$result->code = CodesUtility::TRANSACTION_CODE_SUCCESS;
				$result->msg = "";
				$result->operation_xid = $ret_result->operation_xid;
			}else{
				$result->value = 0;
				$result->code = CodesUtility::TRANSACTION_CODE_ERROR_EXTERNAL;
				$result->msg = $ret_result->result;
			}
		}
 		return $result;
 	}
 	
 	function logResponse ($result)
	{
		ob_start ();
		//print_r($result);
		$res_print = ob_get_clean ();
		
		Zend_Loader::loadClass("Zend_Session_Namespace");
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		
		file_put_contents($client_session->CLIENT_DIR . '/logs/card_log.txt',$res_print . "\n\r" , FILE_APPEND);
	}
	
	function logResult ($result)
	{
		Zend_Loader::loadClass("CADUtility");
		Zend_Loader::loadClass("Zend_Session_Namespace");
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		if($result){
			if(is_array($result)){
				$result = CADUtility::cadImplode($result,",");
			}
		}
		
		file_put_contents($client_session->CLIENT_DIR . '/logs/card_log.txt',$result . "\n\r" , FILE_APPEND);
	}

	
	function logParams ($params = array(),$post_url = "")
	{
		if (isset($params)) {
            // If fields is an array then turn it into a string. Somtimes
            if (is_array($params)) {
                $sets = array();
                foreach ($params as $key => $val) {
                    $sets[] = $key . '=' . urlencode($val);
                }
                $fields = implode('&',$sets);
            } else {
                $fields = $params;
            }
			
			Zend_Loader::loadClass("Zend_Session_Namespace");
			$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		
			file_put_contents($client_session->CLIENT_DIR . '/logs/card_params.txt',$fields . " " . $post_url . "\n\r", FILE_APPEND);
        }
	}
	
	function logXml ($xml)
	{
		Zend_Loader::loadClass("Zend_Session_Namespace");
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
			
		file_put_contents($client_session->CLIENT_DIR . '/logs/card_xml.txt',$xml .  "\n\r", FILE_APPEND);
	}
	
	function logMsg ($msg)
	{
		//print_r($msg);
		Zend_Loader::loadClass("Zend_Session_Namespace");
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		
		file_put_contents($client_session->CLIENT_DIR . '/logs/card_log.txt',$msg . "\n\r" , FILE_APPEND);
	}
	
}
?>